import time
import threading
import asyncio


count = 0


async def async_task(id):
    global count
    while True:
        count += 1
        print(f"async task id:{id} count: {count}")
        await asyncio.sleep(1)


# 方法1: 不推荐
# asyncio.run() 运行异步函数
def run_async_task():
    asyncio.run(async_task("lili"))


# 方法2: 推荐
# 使用新的事件循环
def new_loop_runAsync():
    try:
        # 为当前线程创建独立的事件循环
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(async_task("jack"))
    except Exception as e:
        print(f"Task error: {e}")
    finally:
        if loop and not loop.is_closed():
            loop.close()


if __name__ == "__main__":
    t1 = threading.Thread(target=run_async_task)
    t2 = threading.Thread(target=new_loop_runAsync)
    t1.start()
    t2.start()
    while True:
        cmd = input(">>>")
        print("read key:", cmd)
        if cmd == "q":
            break
        time.sleep(1)
